package org.jaaksi.demo.ptr.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import org.jaaksi.demo.ptr.R;
import org.jaaksi.demo.ptr.api.NetApi;
import org.jaaksi.demo.ptr.bean.house.HouseListBean;
import org.jaaksi.demo.ptr.bean.house.MainResponse;
import org.jaaksi.demo.ptr.bean.response.Result;
import org.jaaksi.demo.ptr.ptr.header.TaoBaoHeader;
import org.jaaksi.demo.ptr.ui.recycler.BaseRecyclerViewFragment;
import org.jaaksi.demo.ptr.ui.recycler.HouseAdapter;
import retrofit.call.SimpleCallback;
import retrofit.util.ServiceGenerator;
import retrofit2.Call;

/**
 * Created by Fcy on 2016/3/17.<br/>
 */
public class MyListActivity extends FragmentActivity
    implements BaseRecyclerViewFragment.RequestCallback {

  private BaseRecyclerViewFragment<HouseListBean> mFragment;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_house_list);

    mFragment = new BaseRecyclerViewFragment<>();
    mFragment.autoLoading(true)
        .pageSize(30)
        .showNoMore(false)
        .setPtrHeader(new TaoBaoHeader(this))
        .setRequestCallback(MyListActivity.this)
        .adapter(new HouseAdapter());

    getSupportFragmentManager().beginTransaction().add(R.id.container, mFragment).commit();
  }

  @Override public void doRequest() {
    Call<Result<MainResponse>> call = ServiceGenerator.createService(NetApi.class)
        .getMainResponse("110000", mFragment.getOffset(), mFragment.getPageSize());
    // 如果是统一请求则无需重新创建，只需要call.clone
    String url = call.request().url().toString();
    Log.i("fcy", "----------------- url=" + url);
    //call.clone().enqueue();
    //Call<Result<MainResponse>> clone = call.clone();

    call.enqueue(new SimpleCallback<Result<MainResponse>>() {
      @Override public void onResponse(Call<Result<MainResponse>> call, Result<MainResponse> entity,
          boolean isSuccess) {
        if (isSuccess && entity.data != null && entity.data.resblock_list != null) {
          // 如果使用服务器hasMore字段，则调用setDatas两个参数的方法，
          // 否则要调用initTotalPages设置总个数，且调用一个参数的方法
          // initTotalPages(
          // response.data.resblock_list.total_count);
          mFragment.setDatas(entity.data.resblock_list.list,
              entity.data.resblock_list.has_more_data == 1);
        } else { // 如果list=null，就设置为null,true
          mFragment.setDatas(null, true);
        }
      }
    });
  }

  public void onClick(View view) {
    mFragment.getRecyclerView().smoothScrollToPosition(0);
  }
}
